<!--
 * 通用文件预览组件
 * 1. 仅用 Element Plus + SCSS，移除 ant-design-vue / WindiCSS
 * 2. 保持原有功能、布局
 * 3. 增加中文注释
-->
<template>
  <div class="file-preview">
    <!-- PDF 渲染 -->
    <div v-if="fileType === 'pdf'" class="pdf-wrapper">
      <vue-pdf-embed
        :source="fileUrl"
        :page="page"
        :scale="scale"
        @loaded="onPdfLoaded"
      />
      <!-- 翻页控制 -->
      <div v-if="totalPages > 1" class="pdf-controls">
        <el-button size="small" :disabled="page <= 1" @click="page--">
          上一页
        </el-button>
        <span class="page-info">{{ page }} / {{ totalPages }}</span>
        <el-button size="small" :disabled="page >= totalPages" @click="page++">
          下一页
        </el-button>
      </div>
    </div>

    <!-- 图片预览 -->
    <img
      v-else-if="fileType === 'image'"
      :src="fileUrl"
      class="image-preview"
      @click="openImagePreview"
    />

    <!-- 不支持的格式 -->
    <div v-else class="unsupported">
      <el-alert
        :title="`不支持的文件类型：${fileType}`"
        type="warning"
        show-icon
        :closable="false"
      />
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref, onMounted } from "vue";
import VuePdfEmbed from "vue-pdf-embed";

/* ------------ props ------------ */
const props = defineProps({
  fileUrl: {
    type: String,
    required: true,
  },
});

/* ------------ 响应式数据 ------------ */
const page = ref(1);
const totalPages = ref(0);
const scale = ref(1); // 如需缩放可动态绑定

/* ------------ 计算属性 ------------ */
/** 根据文件后缀判断类型 */
const fileType = computed(() => {
  if (!props.fileUrl) return "unsupported";
  const ext = props.fileUrl.split(".").pop()?.toLowerCase();
  if (ext === "pdf") return "pdf";
  if (["jpg", "jpeg", "png", "gif", "webp"].includes(ext!)) return "image";
  return "unsupported";
});

/* ------------ 业务方法 ------------ */
/** PDF 加载完成回调 */
function onPdfLoaded(e: { numPages: number }) {
  totalPages.value = e.numPages;
  page.value = 1; // 重置为第一页
}

/** 在新窗口查看原图 */
function openImagePreview() {
  window.open(props.fileUrl, "_blank");
}

/* ------------ 生命周期 ------------ */
onMounted(() => {
  // 可在此处根据 fileType 做额外初始化
});
</script>

<style lang="scss" scoped>
/* ========= 变量 ========= */
$max-width: 100%;
$image-max-height: 600px;
$controls-gap: 12px;

/* ========= 基础样式 ========= */
.file-preview {
  max-width: $max-width;
  text-align: center;
}

/* PDF 区域 */
.pdf-wrapper {
  width: 100%;
}

.pdf-controls {
  margin-top: $controls-gap;
  display: flex;
  justify-content: center;
  align-items: center;
  gap: $controls-gap;

  .page-info {
    font-size: 14px;
    color: #606266;
  }
}

/* 图片预览 */
.image-preview {
  max-width: $max-width;
  max-height: $image-max-height;
  cursor: zoom-in;
}

/* 不支持的文件提示 */
.unsupported {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: 120px;
}
</style>
